package com.youlu.campus.starter.sms.sender;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.youlu.campus.starter.sms.bean.SmsFeiXinOneParam;
import com.youlu.campus.starter.sms.bean.SmsFeiXinResult;
import com.youlu.campus.starter.sms.bean.SmsFeiXinSendResult;
import com.youlu.campus.starter.sms.enums.FeiXinApiUrlEnum;
import com.youlu.campus.starter.sms.properties.SmsFeiXinProperties;
import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * @Description: SmsSender
 * @Date 2025/7/5
 * @module SmsSender
 * @author: su
 */
@Slf4j
@Component
public class SmsFeiXinSender {

    @Resource(name = "smsOkHttpClient")
    private OkHttpClient okHttpClient;

    @Autowired
    private SmsFeiXinProperties smsFeiXinProperties;

    /**
     * 相同内容群发
     *
     * @param phone
     * @param message
     */
    public SmsFeiXinResult sendBatch(String phone, String message) {
        try {
            String timestamp = System.currentTimeMillis() + "";
            String sign = md5(smsFeiXinProperties.getAppkey() + smsFeiXinProperties.getAppsecret() + timestamp);

            // 创建请求体
            FormBody formBody = new FormBody.Builder()
                    .add("appkey", smsFeiXinProperties.getAppkey())
                    .add("appcode", smsFeiXinProperties.getAppcode())
                    .add("appsecret", smsFeiXinProperties.getAppsecret())
                    .add("timestamp", timestamp)
                    .add("sign", sign)
                    .add("phone", phone)
                    .add("msg", message)
                    //.add("extend", "86")
                    .build();
            // 创建请求
            Request request = new Request.Builder()
                    .url(FeiXinApiUrlEnum.BATCH.getApiUrl())
                    .post(formBody)
                    .build();
            // 发送请求并处理响应
            try (Response response = okHttpClient.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    return JSONObject.parseObject(JSONObject.toJSONString(response.body()), SmsFeiXinResult.class);
                } else {
                    log.info("sendBatch Request failed with status code: " + response.code());
                }
            } catch (IOException e) {
                log.error("sendBatch e:{}", e.getMessage(), e);
            }
        } catch (Exception e) {
            log.error("sendBatch e:{}", e.getMessage(), e);
        }
        return SmsFeiXinResult.fail("500", "发送失败");
    }

    /**
     * 一对一批量发送
     *
     * @param smsParam
     */
    public SmsFeiXinResult sendOne2OneBatch(List<SmsFeiXinOneParam> smsParam) {
        try {
            String timestamp = System.currentTimeMillis() + "";
            String sign = md5(smsFeiXinProperties.getAppkey() + smsFeiXinProperties.getAppsecret() + timestamp);
            // 创建请求体
            FormBody formBody = new FormBody.Builder()
                    .add("appkey", smsFeiXinProperties.getAppkey())
                    .add("appcode", smsFeiXinProperties.getAppcode())
                    .add("appsecret", smsFeiXinProperties.getAppsecret())
                    .add("timestamp", timestamp)
                    .add("sign", sign)
                    .add("msg", JSONObject.toJSONString(smsParam))
                    .build();
            // 创建请求
            Request request = new Request.Builder()
                    .url(FeiXinApiUrlEnum.DISTINCT.getApiUrl())
                    .post(formBody)
                    .build();
            // 发送请求并处理响应
            try (Response response = okHttpClient.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    return JSONObject.parseObject(JSONObject.toJSONString(response.body()), SmsFeiXinResult.class);
                } else {
                    log.info("sendOne2OneBatch Request failed with status code: " + response.code());
                }
            } catch (IOException e) {
                log.error("sendOne2OneBatch e:{}", e.getMessage(), e);
            }
        } catch (Exception e) {
            log.error("sendOne2OneBatch e:{}", e.getMessage(), e);
        }
        return SmsFeiXinResult.fail("500", "发送失败");
    }

    /**
     * 批量获取 发送报告
     *
     * @param number
     */
    public List<SmsFeiXinSendResult> reportBatch(int number) {
        try {
            String timestamp = System.currentTimeMillis() + "";
            String sign = md5(smsFeiXinProperties.getAppkey() + smsFeiXinProperties.getAppsecret() + timestamp);
            // 创建请求体
            FormBody formBody = new FormBody.Builder()
                    .add("appkey", smsFeiXinProperties.getAppkey())
                    .add("appcode", smsFeiXinProperties.getAppcode())
                    .add("appsecret", smsFeiXinProperties.getAppsecret())
                    .add("timestamp", timestamp)
                    .add("sign", sign)
                    .add("number", number + "")
                    .build();
            // 创建请求
            Request request = new Request.Builder()
                    .url(FeiXinApiUrlEnum.REPORT.getApiUrl())
                    .post(formBody)
                    .build();
            // 发送请求并处理响应
            try (Response response = okHttpClient.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    String result = response.body().string();
                    log.info(result);
                    return JSONArray.parseArray(JSONObject.toJSONString(response.body()), SmsFeiXinSendResult.class);
                } else {
                    log.info("sendOne2OneBatch Request failed with status code: " + response.code());
                }
            } catch (IOException e) {
                log.error("sendOne2OneBatch e:{}", e.getMessage(), e);
            }
        } catch (Exception e) {
            log.error("sendOne2OneBatch e:{}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * 生成md5签名
     *
     * @param param
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    private static String md5(String param) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] md5Byte = md5.digest(param.getBytes("utf8"));
        String result = byteToHex(md5Byte);
        return result;
    }

    private static String byteToHex(byte[] md5Byte) {
        String result = "";
        StringBuilder sb = new StringBuilder();
        for (byte each : md5Byte) {
            int value = each & 0xff;
            String hex = Integer.toHexString(value);
            if (value < 16) {
                sb.append("0");
            }
            sb.append(hex);
        }
        result = sb.toString();
        return result;
    }
}
